//
//  HomePageController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/24.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON
import MJRefresh

/// 首页

class HomePageController: BaseViewController {

    @IBOutlet weak var navBgview: UIView!
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var navHeight: NSLayoutConstraint!
    
    var tblHeaderView:HomePageHeader!
    
    var newsArray = [NewsModel]()
    var indexModel:IndexModel!
    var budingGoodsArray = [SiteGoodsModel]() // 捆绑商品
    var randomGoodsArray = [SiteGoodsModel]() // 底部商品
    var manufacturersArray = [FireSiteModel]() // 厂商推荐
    var indexNewGoodsArray = [SiteGoodsModel]() // 新品推荐
    
    var randompage = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        

        self.initHeaderView()
        self.navHeight.constant = Utils.isIphoneX() ? 88 : 64
        self.tabBarController?.delegate = self
        
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.randompage = 1
            self?.allRequest()
        })
        
        self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
            self?.randompage = (self?.randompage)! + 1
            self?.getIndexRandom {
                self?.tableView.reloadData()
            }
        })
        
        self.allRequest()
        
        if UserDefaults.standard.object(forKey: "token") as? String == nil {
            Utils.DispatchAfter(after: 3) {
                Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: true)
            }
        }
        NotificationCenter.default.addObserver(self, selector: #selector(logined), name: NSNotification.Name(rawValue: "logined"), object: nil)
    }
    
    @objc func logined(){
        if UserDefaults.standard.object(forKey: "token") as? String == nil {
            Utils.DispatchAfter(after: 3) {
                Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: true)
            }
        }
        self.randompage = 1
        self.allRequest()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    // MARK:手写单
    @IBAction func rightButtonAction(_ sender: UIButton) {
        let ctrl = CameraViewController()
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    

}


extension HomePageController {
    
    func initHeaderView(){
        self.tblHeaderView = HomePageHeader.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 0))
        self.tblHeaderView.backBannerIndex = { [weak self] (index) in
            let model = self?.indexModel.banners![index]
            // 0 id  1 h5
            if model?.type == 0 {
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
                ctrl.hidesBottomBarWhenPushed = true
                ctrl.goodsID = Int((model?.content)!)!
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }else{
                let ctrl = NewsDetailViewController()
                ctrl.url = (model?.content)!
                ctrl.hidesBottomBarWhenPushed = true
                ctrl.titleString = (model?.title)!
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }
        }
        self.tableView.tableHeaderView = self.tblHeaderView
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor.backgroundColor
        self.tblHeaderView.loginedClosure = { [weak self] in
            
            if (UIApplication.shared.delegate as! AppDelegate).isShowLogin == false {
                (UIApplication.shared.delegate as! AppDelegate).isShowLogin = true
                PKhud.showText(text: "请先登录~")
                let vc = Utils.instantiateInitialViewControllerWith(storyBoardName:"Main", identitier: "LoginViewController") as! LoginViewController
                vc.hidesBottomBarWhenPushed = true
                self?.present(UINavigationController.init(rootViewController: vc), animated: true, completion: nil)
            }
            
        }
        
        self.tblHeaderView.backSeleGoodsid = { [weak self] (goodsID)in
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
            ctrl.hidesBottomBarWhenPushed = true
            ctrl.goodsID = goodsID
            self?.navigationController?.pushViewController(ctrl, animated: true)
        }
        
        let tblFooter = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 26))
        tblFooter.backgroundColor = UIColor.backgroundColor
        self.tableView.tableFooterView = tblFooter
        
        if #available(iOS 11, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        }else{
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
}

extension HomePageController:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return self.budingGoodsArray.count
        case 1:
            return self.indexNewGoodsArray.count / 2
        case 2:
            return 1
        case 3:
            return self.randomGoodsArray.count/2
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            return 146
        case 1,3:
            self.tableView.rowHeight = UITableViewAutomaticDimension
            self.tableView.estimatedRowHeight = 220
            return self.tableView.rowHeight
        case 2:
            return 195
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        switch indexPath.section {
        case 0:
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "LeftStyleTableViewCell") as! LeftStyleTableViewCell
                cell.reload(with: self.budingGoodsArray[indexPath.row])
                return cell
            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "RightStyleTableViewCell") as! RightStyleTableViewCell
                cell.reload(with: self.budingGoodsArray[indexPath.row])
                return cell
            }
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "NewGoodsTableViewCell") as! NewGoodsTableViewCell
            cell.reload(withLeftGoods: self.indexNewGoodsArray[indexPath.row * 2], rightGoods: self.indexNewGoodsArray[indexPath.row * 2 + 1])
            cell.seleClosure = { [weak self] (value) in
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
                ctrl.hidesBottomBarWhenPushed = true
                ctrl.goodsID = value
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }
            cell.loginClosure = { [weak self] in
                if (UIApplication.shared.delegate as! AppDelegate).isShowLogin == false {
                    (UIApplication.shared.delegate as! AppDelegate).isShowLogin = true
                    PKhud.showText(text: "请先登录~")
                    let vc = Utils.instantiateInitialViewControllerWith(storyBoardName:"Main", identitier: "LoginViewController") as! LoginViewController
                    vc.hidesBottomBarWhenPushed = true
                    self?.present(UINavigationController.init(rootViewController: vc), animated: true, completion: nil)
                }
            }
            return cell
            
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ManufacturerTableViewCell") as! ManufacturerTableViewCell
            cell.reload(withManufacturerArray: self.manufacturersArray)
            cell.seleClosure = { [weak self] (value) in
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ManufacturerViewController") as! ManufacturerViewController
                ctrl.hidesBottomBarWhenPushed = true
                ctrl.manufacturerArray = (self?.manufacturersArray)!
                ctrl.index = value
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }
            return cell
            
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: "NewGoodsTableViewCell") as! NewGoodsTableViewCell
            cell.reload(withLeftGoods: self.randomGoodsArray[indexPath.row * 2], rightGoods: self.randomGoodsArray[indexPath.row * 2 + 1])
            cell.seleClosure = { [weak self] (value) in
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
                ctrl.hidesBottomBarWhenPushed = true
                ctrl.goodsID = value
                self?.navigationController?.pushViewController(ctrl, animated: true)
            }
            cell.loginClosure = { [weak self] in
                if (UIApplication.shared.delegate as! AppDelegate).isShowLogin == false {
                    (UIApplication.shared.delegate as! AppDelegate).isShowLogin = true
                    PKhud.showText(text: "请先登录~")
                    let vc = Utils.instantiateInitialViewControllerWith(storyBoardName:"Main", identitier: "LoginViewController") as! LoginViewController
                    vc.hidesBottomBarWhenPushed = true
                    self?.present(UINavigationController.init(rootViewController: vc), animated: true, completion: nil)
                }
            }
            
            return cell
        default:
            return UITableViewCell()
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 45
        case 1:
            return 38.5
        case 3:
            return 5
        default:
            return 0.01
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 60
        case 3:
            return 35
        default:
            return 10
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
            ctrl.hidesBottomBarWhenPushed = true
            ctrl.goodsID = self.budingGoodsArray[indexPath.row].id
            ctrl.type = .spare
            self.navigationController?.pushViewController(ctrl, animated: true)
        }
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 45))
            header.backgroundColor = UIColor.nav_color
            
            let bgView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: header.width, height: 30))
            bgView.backgroundColor = UIColor.backgroundColor
            header.addSubview(bgView)
            
            let img = UIImageView.init(image: UIImage.init(named: "btyangshi_2"))
            img.frame = CGRect.init(x: 12, y: 0, width: 22, height: 10)
            img.centerY = bgView.centerY
            bgView.addSubview(img)
            
            let moreBtn = UIButton.init(type: .custom)
            moreBtn.frame = CGRect.init(x: header.width - 12 - 60, y: 0, width: 80, height: 30)
            moreBtn.setTitle("更多", for: .normal)
            moreBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            moreBtn.setTitleColor(UIColor.init(hexColor: "#666666"), for: .normal)
            moreBtn.addTarget(self, action: #selector(getMoreMethod(sender:)), for: .touchUpInside)
            moreBtn.tag = 101
            moreBtn.setImage(UIImage.init(named: "more"), for: .normal)
            moreBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 9)
            moreBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 51, 0, 0)
            bgView.addSubview(moreBtn)
            
            // 文章标题
            let essayLabel = UILabel.init(frame: CGRect.init(x: img.right + 10, y: 0, width: UIScreen.ScreenWidth - img.right - 92, height: 30))
            essayLabel.font = UIFont.systemFont(ofSize: 12)
            essayLabel.textColor = UIColor.init(hexColor: "#333333")
            essayLabel.text = self.newsArray.first?.title
            essayLabel.textAlignment = .left
            bgView.addSubview(essayLabel)
            
            return header
        }
        
        if section == 1 {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 38.5))
            header.backgroundColor = UIColor.nav_color
            
            let label = Utils.labelWith(frame: CGRect.init(x: 23, y: 15, width: 60, height: 14), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: .left, textColor: "#000000", text: "新品推荐")
            header.addSubview(label)
            
            let tagImg = UIImageView.init(image: UIImage.init(named: "btyangshi_3"))
            tagImg.frame = CGRect.init(x: 12, y: 0, width: 11, height: 20)
            tagImg.centerY = label.centerY + 2
            header.addSubview(tagImg)
            
            
            let moreBtn = UIButton.init(type: .custom)
            moreBtn.frame = CGRect.init(x: header.width - 12 - 60, y: 0, width: 80, height: 38.5)
            moreBtn.centerY = label.centerY
            moreBtn.setTitle("更多", for: .normal)
            moreBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            moreBtn.setTitleColor(UIColor.init(hexColor: "#666666"), for: .normal)
            moreBtn.addTarget(self, action: #selector(getMoreMethod(sender:)), for: .touchUpInside)
            moreBtn.tag = 103
            moreBtn.setImage(UIImage.init(named: "more"), for: .normal)
            moreBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 9)
            moreBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 51, 0, 0)
            header.addSubview(moreBtn)
            
            return header
            
        }
        
        if section == 3 {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 5))
            header.backgroundColor = UIColor.nav_color
            return header
        }
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            // 164  94
            let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 60))
            footer.backgroundColor = UIColor.backgroundColor
            
            let bgView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: footer.width, height: 50))
            bgView.backgroundColor = UIColor.nav_color
            footer.addSubview(bgView)
            
            let moreBtn = UIButton.init(type: .custom)
            moreBtn.frame = CGRect.init(x: 0, y: 0, width: 164/2, height: 94/2)
            moreBtn.centerX = bgView.centerX
            moreBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
            moreBtn.setBackgroundImage(UIImage.init(named: "button_5"), for: .normal)
            moreBtn.addTarget(self, action: #selector(getMoreMethod(sender:)), for: .touchUpInside)
            moreBtn.setTitle("查看更多", for: .normal)
            moreBtn.tag = 102
            moreBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 1, 5, 0)
            bgView.addSubview(moreBtn)
            
            return footer
        }
        
        if section == 3 {
            let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 35))
            footer.backgroundColor = UIColor.nav_color
            
            let getMore = UIButton.init(type: .custom)
            getMore.frame = CGRect.init(x: 0, y: 0, width: 80, height: 35)
            getMore.centerX = footer.centerX
            getMore.setImage(UIImage.init(named: "morre_2"), for: .normal)
            getMore.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 8, 0)
            getMore.tag = 104
            getMore.addTarget(self, action: #selector(getMoreMethod(sender:)), for: .touchUpInside)
            footer.addSubview(getMore)
            return footer
        }
        
        return UIView()
    }
    
    
    // MARK:查看更多
    @objc func getMoreMethod(sender:UIButton){
        switch sender.tag - 100 {
        case 2:
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "PreferenceGiftBagTableViewController") as! PreferenceGiftBagTableViewController
            ctrl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 1:
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ZNNewSTableViewController") as! ZNNewSTableViewController
            ctrl.titleString = "智选快报"
            ctrl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 3:
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ManufacturerViewController") as! ManufacturerViewController
            ctrl.hidesBottomBarWhenPushed = true
            ctrl.isNewGoodsRecommend = true
            self.navigationController?.pushViewController(ctrl, animated: true)
        case 4:
            print("商品 获取更多")
        default:
            break
        }
    }
}


extension HomePageController : UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.navBgview.alpha = scrollView.contentOffset.y / 200
    }
    
    func allRequest(){
        let semaphore = DispatchSemaphore.init(value: 0)
        let group = DispatchGroup.init()
        let queue = DispatchQueue.global()
        
        queue.async(group: group) {
            self.getIndexBanner {
                semaphore.signal()
            }
        }
        
        queue.async(group: group) {
            self.getBinding {
                semaphore.signal()
            }
        }
        
        queue.async(group: group) {
            self.getIndexRandom {
                semaphore.signal()
            }
        }
        
        queue.async(group: group) {
            self.getIndexManufactors {
                semaphore.signal()
            }
        }
        
        queue.async(group: group) {
            self.getIndexNew {
                semaphore.signal()
            }
        }
        
        queue.async(group: group) {
            self.getNewsFirst {
                semaphore.signal()
            }
        }
        
        group.notify(queue: queue) {
            semaphore.wait()
            semaphore.wait()
            semaphore.wait()
            semaphore.wait()
            semaphore.wait()
            semaphore.wait()
            DispatchQueue.main.async {
                self.tableView.mj_header.endRefreshing()
                self.tableView.reloadData()
            }
        }
    }
    
    func getNewsFirst(closure:@escaping ()->Void){
        HttpRequest.requestData(.post, URLString: Api.articleList.rawValue, parameters: ["pageNum":1,"pageSize":1]) { (result) in
            PKhud.hiden()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            if result["msg"] as! String == "success"{
                if let array = [NewsModel].deserialize(from: result["data"] as? [Any]) as? [NewsModel] {
                    self.newsArray = array
                    closure()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK: 首页轮播图和爆品直降
    func getIndexBanner(closure:@escaping ()->Void){
        HttpRequest.requestData(.post, URLString: Api.index.rawValue, parameters: nil) { (result) in
            if result["msg"] as! String == "success"{
                if let jsonDic = result["data"] as? postParameters{
                    let model = JSONDeserializer<IndexModel>.deserializeFrom(dict: jsonDic)
                    self.indexModel = model
                    self.tblHeaderView.updateSubViews(WithModel: self.indexModel)
                    closure()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    // MARK:捆绑商品  首页和列表页通用
    func getBinding(closure:@escaping ()->Void){
        
        HttpRequest.requestData(.post, URLString: Api.indexBinding.rawValue, parameters: ["pageNum":1,"pageSize":2]) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel]{
                    self.budingGoodsArray = array
                    closure()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:首页底部商品
    func getIndexRandom(closure:@escaping ()->Void){
        HttpRequest.requestData(.post, URLString: Api.indexRandom.rawValue, parameters: ["pageNum":self.randompage,"pageSize":12]) { (result) in
            if result["msg"] as! String == "success"{
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel] {
                    if self.randompage == 1 {
                        self.randomGoodsArray = array
                    }else{
                        self.randomGoodsArray = self.randomGoodsArray + array
                    }
                    if array.count < 12 {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    closure()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:获取厂商直销
    func getIndexManufactors(closure:@escaping ()->Void){
        HttpRequest.requestData(.post, URLString: Api.indexManufactors.rawValue, parameters: nil) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [FireSiteModel].deserialize(from: result["data"] as? [Any]) as? [FireSiteModel] {
                    self.manufacturersArray = array
                    closure()
                }
                
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:获取新品推荐
    func getIndexNew(closure:@escaping ()->Void){
        HttpRequest.requestData(.post, URLString: Api.indexNnew.rawValue, parameters: ["pageSize":4,"pageNum":1]) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel]{
                    self.indexNewGoodsArray = array
                    closure()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
}



























